package com.xcf.leetcode;

/**
 * LongSamePrefix <br>
 * 写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * 说明:
 * <p>
 * 所有输入只包含小写字母 a-z 。
 *
 * @author xiaocf <br>
 * @version 1.0 <br>
 * @date 2020/7/6 19:51 <br>
 */
public class LongSamePrefix {

    public String longestCommonPrefix(String[] strs) {
        if (strs.length <= 0) {
            return "";
        }
        StringBuilder builder = new StringBuilder( );
        String baseStr = strs[0];
        int index = 0;
        while (true) {
            if (index >= baseStr.length( )) {
                return builder.length( ) > 0 ? builder.toString( ) : "";
            }
            char charAt = baseStr.charAt(index);
            for (String str : strs) {
                if (index >= str.length() || str.charAt(index) != charAt) {
                    return builder.length( ) > 0 ? builder.toString( ) : "";
                }
            }
            builder.append(charAt);
            index++;
        }
    }

    public static void main(String[] args) {
        LongSamePrefix prefix = new LongSamePrefix( );
        String prefixStr = prefix.longestCommonPrefix(new String[]{"flower", "flow", "flight"});
        System.out.println("prefixStr = " + prefixStr);
        prefixStr = prefix.longestCommonPrefix(new String[]{"dog","racecar","car"});
        System.out.println("prefixStr = " + prefixStr);
    }
}
